import os
os.chdir('..')
dir = ['doctool']
for i in dir:
    os.chdir(i)
    cases = [x for x in os.listdir() if x[-3:] == 'mjs']
    exitcodes = [x for x in os.listdir() if x[-4:] == 'code']
    if (len(cases) == 0):
        print(f'No test cases in {i}')
        os.chdir('..')
        continue
    failed = []
    succeeded = []

    for x in exitcodes:
        with open(x, 'r') as f:
            code = f.read(1)
            if code != '0':
                failed.append(x[:-9])
            else:
                succeeded.append(x[:-9])
    os.chdir('..')

    lines = []
    lines.append(f'# {i}_report\n\n')
    lines.append(f'## 使用脚本\n\n')
    lines.append(f'[运行测试使用的脚本](../script/test3.py)\n\n')
    lines.append(f'[生成测试报告使用的脚本](../script/process3.py)\n\n')

    lines.append(f'## 数量\n\n')
    lines.append(f'### Total tests: {len(cases)}\n\n')

    lines.append(f'[log](../log/{i}_log.md)\n\n')

    lines.append(f'## 通过脚本\n\n')
    lines.append(f'### Passed tests: {len(succeeded)}\n\n')
    for case in succeeded:
        lines.append(f'- {case}\n\n')

    lines.append(f'## 失败脚本\n\n')
    lines.append(f'### Failed tests: {len(failed)}\n\n')
    for case in failed:
        lines.append(f'- {case}\n\n')

    with open(f'r/{i}_report.md', 'w', encoding='utf-8') as f:
        f.writelines(lines)

    lines = []
    lines.append(f'# {i}_log\n\n')
    for case in cases:
        try:
            lines.append(f'## {case}\n\n')
            with open(f'{i}/{case}.exitcode', 'r') as f:
                code = f.readline()
            lines.append(f'Exit code: {code}\n\n')

            with open(f'{i}/{case}.out', 'r', encoding='utf-8') as f:
                if f.read() == '':
                    pass
                else:
                    lines.append('stdout:\n\n')
                    lines.append(f'```text\n')
                    f.seek(0)
                    lines.extend(f.readlines())
                    lines.append(f'\n```\n\n')

            with open(f'{i}/{case}.err', 'r', encoding='utf-8') as f:
                if f.read() == '':
                    pass
                else:
                    lines.append('stderr:\n\n')
                    lines.append(f'```text\n')
                    f.seek(0)
                    lines.extend(f.readlines())
                    lines.append(f'\n```\n\n')

        except FileNotFoundError:
            pass
        with open(f'log/{i}_log.md', 'w', encoding='utf-8') as f:
            f.writelines(lines)
